// eslint-disable-next-line react-compiler/react-compiler
/* eslint-disable react-hooks/exhaustive-deps */
import Loading from '@/components/Loading'
import NotFound from '@/components/NotFound'
import { ROUTER_PATHS_PUBLIC } from '@/constants/global'
import { SLASH_ROUTE_CHILDREN } from '@/router'
import { flatDeep } from '@/utils/array'
import useUserInfo from '@/zustand/useUserInfo'
import type { ReactNode } from 'react'
import { useEffect, useState } from 'react'
import { useMatch, useNavigate } from 'react-router-dom'

let timer = 0

export default function AuthComponent(props: { children?: ReactNode }) {
  const match = useMatch('/*')
  /** 👇 路由跳转 👇 */
  const navigate = useNavigate()

  const userMenus = useUserInfo((s) => s.userMenus)
  const setMenuSelectedKeys = useUserInfo((s) => s.setMenuSelectedKeys)
  /** 👇 是否有页面权限 👇 */
  const [auth, setAuth] = useState(false)
  /** 👇 登录状态校验是否成功; 默认值一定要为 false, 默认值为 true 时, 会有 NotFound 一闪而过的情况 👇 */
  const [check, setCheck] = useState(false)

  /** 👇 页面鉴权的逻辑 👇 */
  useEffect(() => {
    timer = window.setTimeout(() => {
      console.log('AuthComponent:match?.pathname:', match?.pathname)

      /** 👇 当前路径是否为 / 👇 */
      if (match?.pathname === ROUTER_PATHS_PUBLIC.SLASH) {
        const path = userMenus?.[0].path
        if (path) navigate(path, { replace: true })
      } else {
        /** 👇 侧栏菜单选中项 👇 */
        setMenuSelectedKeys(
          match?.pathname
            ?.split('/')
            ?.map((_, i, arr) => arr.filter((_, i2) => i2 <= i).join('/'))
            ?.filter((v) => v) || []
        )
        /** 👇 路由中是否配置了当前页面 👇 */
        const hasPage = flatDeep(SLASH_ROUTE_CHILDREN, 'children').find(
          (c) => c.path === match?.pathname
        )
        /** 👇 是否有当前页面权限 👇 */
        const hasAuth = userMenus.some((c) => c.path === match?.pathname)
        if (hasPage) {
          if (hasAuth) setAuth(true)
        }
        setCheck(true)
      }
    }, 10)

    return () => {
      setCheck(false)
      setAuth(false)
      if (timer) window.clearTimeout(timer)
    }
  }, [match?.pathname])

  return (
    <div className="h-[100%]" data-name="AuthComponent">
      {check ? auth ? props.children : <NotFound /> : <Loading />}
    </div>
  )
}
